package com.eshop.utils;

import java.util.Collection;
import org.springframework.util.CollectionUtils;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.List;

public class TreeUtil
{
    public static List<CateDTO> list2TreeConverter(final List<CateDTO> list, final int parentId) {
        final List<CateDTO> returnList = new ArrayList<CateDTO>();
        for (final CateDTO res : list) {
            if (res.getPid() == parentId) {
                recursionFn(list, res);
                returnList.add(res);
            }
        }
        return returnList;
    }
    
    public static void recursionFn(final List<CateDTO> list, final CateDTO t) {
        final List<CateDTO> childsList = getChildList(list, t);
        t.setChildren(childsList);
        for (final CateDTO nextChild : childsList) {
            if (!CollectionUtils.isEmpty((Collection)childsList)) {
                recursionFn(list, nextChild);
            }
        }
    }
    
    public static List<CateDTO> getChildList(final List<CateDTO> list, final CateDTO t) {
        final List<CateDTO> childsList = new ArrayList<CateDTO>();
        for (final CateDTO t2 : list) {
            if (t2.getPid().equals(t.getId())) {
                childsList.add(t2);
            }
        }
        return childsList;
    }
    
    public static boolean hasChild(final List<CateDTO> list, final CateDTO t) {
        return getChildList(list, t).size() > 0;
    }
}
